package com.itany.ums.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.itany.ums.dao.UserDao;
import com.itany.ums.entity.User;

import data.Database;

public class UserDaoImplForMap implements UserDao {

	@Override
	public User selectByLoginnameAndPassword(String loginname, String password) {
		for (User u : Database.users.values()) {
			if ((u.getUsername().equals(loginname) || u.getPhone().equals(loginname) || u.getEmail().equals(loginname)) && u.getPassword().equals(password)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public User selectByUsername(String username) {
		for (User u : Database.users.values()) {
			if (u.getUsername().equals(username)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public User selectByPhone(String phone) {
		for (User u : Database.users.values()) {
			if (u.getPhone().equals(phone)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public User selectByEmail(String email) {
		for (User u : Database.users.values()) {
			if (u.getEmail().equals(email)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public void saveUser(User u) {
		u.setId(Database.id++);
		Database.users.put(u.getId(), u);
	}

	@Override
	public User selectById(long id) {
		return Database.users.get(id);
	}

	@Override
	public void updatePwd(long id, String newPwd) {
		Database.users.get(id).setPassword(newPwd);
	}

	@Override
	public void updateUsername(long id, String username) {
		Database.users.get(id).setUsername(username);
	}

	@Override
	public List<User> selectByRole(int roleCode) {
		List<User> users = new ArrayList<User>();
		for (User u : Database.users.values()) {
			if (u.getRole().equals(roleCode)) {
				users.add((User) u.clone());
			}
		}
		return users;
	}

	@Override
	public void updateStateById(long id, int stateCode) {
		Database.users.get(id).setState(stateCode);
	}

}
